package com.smart.tools.ip2region;

import com.alibaba.fastjson.JSONObject;
import com.smart.common.utils.CacheUtil;
import com.smart.common.utils.HttpUtil;
import com.smart.common.utils.SpringUtil;
import com.smart.model.weather.ReceiveBusWeather;
import com.smart.model.weather.WeatherEntity;
import com.smart.service.system.ConfigService;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class Ip2RegionUtil {
    private static ConfigService configService;

    public static Ip2RegionUtil ip2RegionUtil;

    //3.容器初始化的时候进行执行-这里是重点
    private static ConfigService getConfigService() {
        if (configService == null) {
            configService = SpringUtil.getBean(ConfigService.class);
        }
        return configService;
    }

    /**
     * 获取ip属地(缓存整个 xdb 数据)
     *
     * @param ip IP地址
     * @return 返回地址
     */
    public static String getCityInfoByMemorySearch(String ip) {
        String fileName = "ip2region.xdb";
        ClassPathResource classPathResource = new ClassPathResource(fileName);
        byte[] cBuff = new byte[0];
        try {
            cBuff = convertInputStreamToByteArray(classPathResource.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //1、从 dbPath 加载整个 xdb 到内存。
        //byte[] cBuff;
        //try {
        //    cBuff = Searcher.loadContentFromFile(dbPath);
        //} catch (Exception e) {
        //    log.error("failed to load content from `{}`: ", dbPath, e);
        //    return null;
        //}

        // 2、使用上述的 cBuff 创建一个完全基于内存的查询对象。
        Searcher searcher;
        try {
            searcher = Searcher.newWithBuffer(cBuff);
        } catch (Exception e) {
            log.error("failed to create content cached searcher: ", e);
            return null;
        }

        // 3、查询
        try {
            long sTime = System.nanoTime();
            String region = searcher.search(ip);
            //long cost = TimeUnit.NANOSECONDS.toMicros(System.nanoTime() - sTime);
            //log.info("{region: {}, ioCount: {}, took: {} μs}\n", region, searcher.getIOCount(), cost);
            return region;
        } catch (Exception e) {
            log.error("failed to search({}): ", ip, e);
        }
        return null;
        // 备注：并发使用，用整个 xdb 数据缓存创建的查询对象可以安全的用于并发，也就是你可以把这个 searcher 对象做成全局对象去跨线程访问。
    }

    public static byte[] convertInputStreamToByteArray(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, length);
        }
        return byteArrayOutputStream.toByteArray();
    }

    public static WeatherEntity getWeatherByIp(String ip) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String region = getCityInfoByMemorySearch(ip);
        String city = region.replace("|", ",").split(",")[3];
        //System.out.println(city);
        WeatherEntity weather = CacheUtil.get("weather", city, WeatherEntity.class);
        //如果不是当天的天气预报就更新,是当天的话就取缓存数据，并且不是默认的城市
        if (weather != null && weather.getReporttime().substring(0, 10).equals(sdf.format(new Date()))&&weather.getIsdefault()==0) {
            return weather;
        }
        weather = new WeatherEntity();
        weather.setIsdefault(1);
        String key = getConfigService().getConfig("bus_gaode_webkey");
        String url = "https://restapi.amap.com/v3/weather/weatherInfo";
        String paramsStr = "key=" + key + "&city=" + city + "&extensions=base";
        String res = HttpUtil.sendGet(url, paramsStr);
        ReceiveBusWeather getEntity = JSONObject.parseObject(res, new ReceiveBusWeather().getClass());
        setDefaultReceiveWeatherEntity(weather);
        if (getEntity.getLives().size() > 0) {
            weather = getEntity.getLives().get(0);
        }
        setWeatherUrl(weather);
        CacheUtil.put("weather", city, weather);
        return weather;
    }

    public static void setDefaultReceiveWeatherEntity(WeatherEntity item){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String city = getConfigService().getConfig("bus_gaode_weather_city");
        String adcode = getConfigService().getConfig("bus_gaode_weather_adcode");
        String weather = getConfigService().getConfig("bus_gaode_weather_weather");
        String temperature = getConfigService().getConfig("bus_gaode_weather_temperature");
        item.setProvince("天津");
        item.setCity(city);
        item.setAdcode(adcode);
        item.setWeather(weather);
        item.setTemperature(temperature);
        item.setWinddirection("东北");
        item.setWindpower("<=4");
        item.setHumidity("67");
        item.setReporttime(sdf.format(new Date()));
        setWeatherUrl(item);
    }
    /**
     * 天气文字转图片
     *
     * @param weatherEntity
     */
    public static void setWeatherUrl(WeatherEntity weatherEntity) {
        String picName = "wu";
        String weather = weatherEntity.getWeather();
        if (weather.equals("大雪")) {
            picName = "daxue";
        } else if (weather.equals("大雨")) {
            picName = "dayu";
        } else if (weather.equals("多云")) {
            picName = "duoyun";
        } else if (weather.equals("风")) {
            picName = "feng";
        } else if (weather.equals("雷阵雨")) {
            picName = "leizhenyu";
        } else if (weather.equals("晴")) {
            picName = "qing";
        } else if (weather.equals("小雪")) {
            picName = "xiaoxue";
        } else if (weather.equals("小雨")) {
            picName = "xiaoyu";
        } else if (weather.equals("扬沙")) {
            picName = "yangsha";
        } else if (weather.equals("雨夹雪")) {
            picName = "yujiaxue";
        } else if (weather.equals("中雪")) {
            picName = "zhongxue";
        } else if (weather.equals("中雨")) {
            picName = "zhongyu";
        }
        String url = "https://pst-test.oss-cn-beijing.aliyuncs.com/mini/lwgzh/" + picName + ".png";
        weatherEntity.setUrl(url);
    }
}
